import json
import requests
from odoo import http
from odoo.http import request
from werkzeug.utils import redirect
from fastapi.encoders import jsonable_encoder
from oauth2client.client import OAuth2WebServerFlow

from ..functions.google_login_func import Google_Login_func


class OrderPayController(http.Controller):

    # 方案一：google OAuth授权接口
    
    # 授权回调接口
    @http.route('/google/auth/success', type='http', auth='public', method=['GET'])
    def google_auth_success(self, *args, **kw):
        """
        Odoo后台中回调【google登录回调成功】
        Params:
        """
        # 根据授权链接获取access_token(访问令牌)
        flag, client_id, client_secret, redirect_uri = Google_Login_func(request.env).get_config_parameter()
        if not flag:
            data = {
                'code':400,
                'message': 'error',
                'data':{}
            }
            return json.dumps(data)
        code = kw.get('code')
        url = 'https://oauth2.googleapis.com/token'
        values = {
            'code': code,
            'client_id': client_id,
            'client_secret': client_secret,
            'redirect_uri': redirect_uri,
            'grant_type': 'authorization_code'
        }
        data = json.dumps(values)
        response = requests.post(url, data=data)
        response_dict = json.loads(response.text)
        # 根据access_token获取用户信息
        user_info_dict = Google_Login_func(request.env).google_get_user_info(response_dict['access_token'])
        # 根据用户信息进行登录或者注册登录
        url = Google_Login_func(request.env).google_login(user_info_dict)
        redirect_url = redirect(url)
        return redirect_url

    # 获取授权链接
    @http.route('/google/auth/login', type='http', auth='public', method=['GET'], csrf=False, cors='*')
    def google_auth_login(self):
        # 定义google OAuth2客户端信息
        scope = 'openid email profile'
        flag, client_id, client_secret, redirect_uri = Google_Login_func(request.env).get_config_parameter()
        if not flag:
            data = {
                'code':400,
                'message': '参数不全',
                'data':{}
            }
            return json.dumps(data, ensure_ascii=False)

        # 创建OAuth2客户端流
        flow = OAuth2WebServerFlow(client_id=client_id,
                                   client_secret=client_secret,
                                   scope=scope,
                                   redirect_uri=redirect_uri,
                                   prompt='select_account')

        # 获取授权链接
        auth_uri = flow.step1_get_authorize_url()
        data = {
            'code':200,
            'message': 'success',
            'data':{'auth_uri': auth_uri}
        }
        return json.dumps(data)
    
    # 方案二：firebase-google授权接口
    
    # 返回firebase配置参数
    @http.route('/get/firebase/config/info', type='http', auth='public', method=['GET'], csrf=False, cors='*')
    def get_firebase_config_info(self):
        apiKey = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_apiKey')
        authDomain = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_authDomain')
        projectId = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_projectId')
        storageBucket = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_storageBucket')
        messagingSenderId = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_messagingSenderId')
        appId = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_appId')
        measurementId = request.env['ir.config_parameter'].sudo().get_param('rp_google_firebase_measurementId')
        if not any([apiKey, authDomain, projectId, storageBucket, messagingSenderId, appId, measurementId]):
            result = {'code': 404,
                      'message': '参数缺失',
                      'data': {}
                    }
        else:
            result = {'code': 200,
                      'message': 'success',
                      'data': {
                          'apiKey': apiKey,
                          'authDomain': authDomain,
                          'projectId': projectId,
                          'storageBucket': storageBucket,
                          'messagingSenderId': messagingSenderId,
                          'appId': appId,
                          'measurementId': measurementId
                        }
                    }
        return json.dumps(result, ensure_ascii=False)
    
    # 根据access_token获取用户信息
    @http.route('/get/google/user/info', type='http', auth='public', method=['GET'], csrf=False, cors='*')
    def get_google_user_info(self, access_token):
        code = 200
        message = 'success'
        user_info_dict = Google_Login_func(request.env).firebase_get_user_info(access_token)
        if not user_info_dict:
            code = 400
            message = 'access_token无效'
        encode_jwt, user = Google_Login_func(request.env).rectaparcel_get_user_info(user_info_dict)
        if not encode_jwt:
            code = 400
            message = '不存在用户'
        data = {'access_token': encode_jwt, 'token_type': "Bearer", 'user': user}
        result = {
            'code':code,
            'message': message,
            'data': data
        }
        return json.dumps(jsonable_encoder(result), ensure_ascii=False)

    # google邮箱发送验证码
    @http.route('/google/mail/send/code', type='http', auth='public', method=['GET'], csrf=False, cors='*')
    def google_mail_send_code(self, mail):
        result = Google_Login_func(request.env).google_mail_send_code(act_one='google_mail', mail=mail)
        return json.dumps(result, ensure_ascii=False)
    
    # google邮箱验证码验证
    @http.route('/google/mail/code/verify', type='http', auth='public', method=['GET'], csrf=False, cors='*')
    def google_mail_code_verify(self, mail, verifyt_code):
        customer_id = request.session.get('order_customer_id')
        result = Google_Login_func(request.env).google_mail_code_verify(mail, verifyt_code, customer_id)
        return json.dumps(result, ensure_ascii=False)
        